<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="工单号" prop="ncrNo">
        <el-input v-model="queryParams.ncrNo" placeholder="请输入工单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="来源单据编号" prop="sourceNo">
        <el-input v-model="queryParams.sourceNo" placeholder="请输入来源单据编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="来源类型" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择来源类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.QUALITY_SOURCE_TYPE)" :key="dict.value"
            :label="dict.label" :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料编码" prop="materialNo">
        <el-input v-model="queryParams.materialNo" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input v-model="queryParams.batchNo" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="原始批次号" prop="rawBatchNo">
        <el-input v-model="queryParams.rawBatchNo" placeholder="请输入原始批次号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input v-model="queryParams.quantity" placeholder="请输入数量" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
      <!-- 仓库选择 -->
        <treeselect v-model="queryParams.warehouseId" :options="warehouseTree" :normalizer="normalizerW"
          placeholder="选择仓库" style="width: 200px" @select="onWarehouseChange" />
      </el-form-item>
      <el-form-item label="库位" prop="storeId">
      <el-select v-model="queryParams.storeId" placeholder="请选择库位" clearable size="small"
        style="width: 200px">
        <el-option v-for="location in locationList" :key="location.id" :label="location.storageLocationName"
          :value="location.id" />
      </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditState">
        <el-select v-model="queryParams.auditState" placeholder="请选择审核状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.AUDIT_STATE)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核结果" prop="auditResult">
        <el-select v-model="queryParams.auditResult" placeholder="请选择审核结果" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.AUDIT_RESULT)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
          v-hasPermi="['quality:ncr-record:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          :loading="exportLoading" v-hasPermi="['quality:ncr-record:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch" v-hasPermi="['quality:ncr-record:delete']">
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="工单号" align="center" prop="ncrNo" width="150" />
      <el-table-column label="来源单据编号" align="center" prop="sourceNo" width="150" />
      <el-table-column label="来源单据类型" align="center" prop="sourceType" width="150">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.QUALITY_SOURCE_TYPE, scope.row.sourceType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" prop="materialNo" width="150" />
      <el-table-column label="批次号" align="center" prop="batchNo" width="150" />
      <el-table-column label="原始批次号" align="center" prop="rawBatchNo" width="150" />
      <el-table-column label="日期" align="center" prop="date" width="150" />
      <el-table-column label="数量" align="center" prop="quantity" width="150" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" width="150" />
      <el-table-column label="库位名称" align="center" prop="storeName" width="150" />
      <el-table-column label="审核状态" align="center" prop="auditState" width="150">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.AUDIT_STATE, scope.row.auditState) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="合格数量" align="center" prop="passQuantity" width="150" />
      <el-table-column label="不合格数量" align="center" prop="failQuantity" width="150" />
      <el-table-column label="报废数量" align="center" prop="scrapQuantity" width="150" />
      <el-table-column label="审核结果" align="center" prop="auditResult" width="150">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.AUDIT_RESULT, scope.row.auditResult) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缺陷名称" align="center" prop="defectName" width="150" />
      <el-table-column label="缺陷比例" align="center" prop="defectRatio" width="150" />
      <el-table-column label="备注" align="center" prop="remark" width="150" />
      <el-table-column label="创建者" align="center" prop="creator" width="150" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template v-slot="scope">
<!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"-->
<!--            v-hasPermi="['quality:ncr-record:update']">修改-->
<!--          </el-button>-->
          <el-button size="mini" type="text" icon="el-icon-check" :disabled="scope.row.auditState == 1" @click="openAuditForm(scope.row)">审核
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['quality:ncr-record:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <NcrRecordForm ref="formRef" @success="getList" />

    <!-- 审核对话框 -->
    <el-dialog title="不良品审核" :visible.sync="auditDialogVisible" width="600px">
      <el-form :model="auditForm" label-width="120px">
        <el-form-item label="合格数量" prop="passQuantity">
          <el-input v-model.number="auditForm.passQuantity" placeholder="请输入合格数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="不合格数量" prop="failQuantity">
          <el-input v-model.number="auditForm.failQuantity" placeholder="请输入不合格数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="报废数量" prop="scrapQuantity">
          <el-input v-model.number="auditForm.scrapQuantity" placeholder="请输入报废数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="审核结果" prop="auditResult" required>
          <el-select v-model="auditForm.auditResult" placeholder="请选择审核结果" style="width: 100%">
            <el-option v-for="dict in this.getDictDatas(DICT_TYPE.AUDIT_RESULT)" :key="dict.value"
              :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷名称" prop="defectName">
          <el-input v-model="auditForm.defectName" placeholder="请输入缺陷名称" />
        </el-form-item>
        <el-form-item label="缺陷比例" prop="defectRatio">
          <el-input v-model="auditForm.defectRatio" placeholder="请输入缺陷比例" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as NcrRecordApi from '@/api/quality/ncrrecord';
import NcrRecordForm from './NcrRecordForm.vue';
import * as WarehouseApi from "@/api/storage/warehouse";
import * as LocationApi from "@/api/storage/location";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "NcrRecord",
  components: {
    NcrRecordForm,
    Treeselect
  },
  data() {
    return {
      // 仓库树数据
      warehouseTree: [],
      // 仓库树加载状态
      treeLoading: false,
      // 库位列表
      locationList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 不良品处理列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        ncrNo: null,
        sourceId: null,
        sourceNo: null,
        sourceType: null,
        materialId: null,
        materialNo: null,
        batchNo: null,
        rawBatchNo: null,
        date: [],
        quantity: null,
        warehouseId: null,
        warehouseName: null,
        storeId: null,
        storeName: null,
        remark: null,
        auditState: null,
        auditResult: null,
        createTime: [],
      },
      // 审核弹框相关数据
      auditDialogVisible: false,
      auditForm: {
        id: null,
        passQuantity: null,
        failQuantity: null,
        scrapQuantity: null,
        auditResult: null,
        defectName: null,
        defectRatio: null
      },
    };
  },
  created() {
    this.getList();
    this.getWarehouseTree();
  },
  methods: {
    /** 根据仓库ID获取库位列表 */
    async getLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationList = [];
      }
    },
    /** 仓库选择变化时触发 */
    async onWarehouseChange(warehouseId) {
      this.queryParams.storeId = null; // 清空库位选择
      if (warehouseId) {
        await this.getLocationList(warehouseId.id); // 根据仓库ID获取库位
      } else {
        this.locationList = []; // 清空库位列表
      }
    },
    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        this.treeLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.$modal.msgError('获取仓库树数据失败');
      } finally {
        this.treeLoading = false;
      }
    },
    /** 树节点标准化处理 */
    normalizerW(node) {
      const result = {
        id: node.id,
        label: node.warehouseName,
        children: undefined
      };
      // 只有当children存在且不为undefined且长度大于0时才添加该字段
      if (node.children && node.children.length > 0) {
        result.children = node.children;
      }
      return result;
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await NcrRecordApi.getNcrRecordPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除不良品处理编号为"' + id + '"的数据项?')
      try {
        await NcrRecordApi.deleteNcrRecord(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除不良品处理 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await NcrRecordApi.deleteNcrRecordList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有不良品处理数据项?');
      try {
        this.exportLoading = true;
        const data = await NcrRecordApi.exportNcrRecordExcel(this.queryParams);
        this.$download.excel(data, '不良品处理.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    /** 打开审核弹框 */
    openAuditForm(row) {
      this.auditForm = {
        id: row.id,
        passQuantity: null,
        failQuantity: null,
        scrapQuantity: null,
        auditResult: null,
        defectName: null,
        defectRatio: null
      };
      this.auditDialogVisible = true;
    },
    /** 提交审核 */
    async submitAudit() {
      try {
        await NcrRecordApi.audit(this.auditForm);
        this.$modal.msgSuccess('审核成功');
        this.auditDialogVisible = false;
        await this.getList();
      } catch (error) {
        console.error('审核失败:', error);
      }
    }
  }
};
</script>
